//
//  CMLoginManager.m
//  CreditManger
//
//  Created by chaiyanan on 15/11/5.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMLoginManager.h"
#import "CMLoginCtrl.h"

#define CurrentUser     @"CurrentUser"

@implementation CMLoginManager

static CMLoginManager *sharedCMLoginManager = nil;

+ (CMLoginManager *)sharedCMLoginManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedCMLoginManager = [[CMLoginManager alloc]init];
    });
    return sharedCMLoginManager;
}

#pragma mark -
#pragma mark - userDefault currentUser Operate

+ (void)cacheCurrentUserToUserDefault:(CMLoginUserInfo *)info
{
    NSData *userInfoData = [NSKeyedArchiver archivedDataWithRootObject:info];
    [[NSUserDefaults standardUserDefaults]setObject:userInfoData forKey:CurrentUser];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [CMLoginManager sharedCMLoginManager].currentUserInfo = info;
    [CMLoginManager sharedCMLoginManager].hasLogined = YES;
    
}

+ (CMLoginUserInfo *)getCurrentUserFromUserdefault
{
    CMLoginUserInfo *info = [[CMLoginUserInfo alloc]init];
    info = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults]objectForKey:CurrentUser]];
    if (info)
    {
        [CMLoginManager sharedCMLoginManager].currentUserInfo = info;
        [CMLoginManager sharedCMLoginManager].hasLogined = YES;
  
    }
    return info;
}

+ (void)deleteCacheCurrentUserFromUserDefault
{
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:CurrentUser];
    [[NSUserDefaults standardUserDefaults]synchronize];
    //    [LC_AUTH_MANAGER saveLockPassword:nil];
    [CMLoginManager sharedCMLoginManager].currentUserInfo = nil;
    [CMLoginManager sharedCMLoginManager].hasLogined = NO;
    
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"CantReceiveVPNMessage"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
}

+ (UIViewController *)getRegisterStepViewControllerOrLoginCtrl
{
    [self getCurrentUserFromUserdefault];
    if ([self sharedCMLoginManager].currentUserInfo)
    {
        if ([self sharedCMLoginManager].hasLogined)
        {
            return nil;
        }
        else
        {
            return [[CMLoginCtrl alloc]init];
        }
    }
    else
    {
        return [[CMLoginCtrl alloc]init];
    }
}

+ (void)didLoginOut
{
    [self deleteCacheCurrentUserFromUserDefault];
    CMLoginCtrl *ctrl = [[CMLoginCtrl alloc] init];
    CMNavigationController *nav = [[CMNavigationController alloc] initWithRootViewController:ctrl];
    CMAppDelegate.window.rootViewController = nav;
    [nav setNavigationBarHidden:YES];
}



@end
